package com.lyc.controller;

import com.lyc.beans.Book;
import com.lyc.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Objects;

@Controller
@RequestMapping("book")
public class BookController {
    @Autowired
    private BookService bookService;

    @RequestMapping("addBook")
    public ModelAndView addBook(String title, String author, String num){
        ModelAndView modelAndView = new ModelAndView();
        Book book = new Book();
        book.setTitle(title);
        book.setAuthor(author);
        if (!num.equals("")){
            book.setNum(Integer.parseInt(num));
        }
            if ( book.getNum()>=0 && !book.getTitle().equals("") && !book.getAuthor().equals("") ){
                //判断书籍是否存在
                boolean b = bookService.checkBook(book);
                if (b){
                    //存在
                    modelAndView.addObject("msg","图书已存在");
                    modelAndView.setViewName("login");
                }else {
                    //不存在
                    bookService.addBook(book);
                    modelAndView.addObject("msg","添加成功");
                    modelAndView.setViewName("login");
                }
            }else {
                modelAndView.addObject("msg","输入不正确");
                modelAndView.setViewName("login");
            }

        return modelAndView;
    }

    @RequestMapping("toAddBook")
    public ModelAndView toAddBook(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("addBook");
        return modelAndView;
    }

    @RequestMapping("deleteBook")
    public ModelAndView deleteBook(Integer id){
        ModelAndView m = new ModelAndView();
        bookService.deleteBookById(id);
        m.setViewName("redirect:/user/toLoginShow");
        return m;
    }

    @RequestMapping("updateBook")
    public ModelAndView updateBook(Book book){
        ModelAndView m = new ModelAndView();

        //判断书籍名字不重复
        Book book1 = bookService.getBookByName(book);

        //判断书籍名字是否重名
        if (book1==null || book1.getId() == book.getId()){
            //不重名,修改
            bookService.updateBook(book);
            m.addObject("msg","修改成功");
            m.setViewName("login");
        }else {

            //重名
            m.addObject("msg","书籍名存在");
            m.setViewName("updateBook");
        }
        return m;
    }

    @RequestMapping("toUpdateBook")
    public ModelAndView toUpdateBook(Integer id){
        ModelAndView m = new ModelAndView();
        m.setViewName("updateBook");
        Book book = bookService.getBookById(id);
        m.addObject("book", book);
        return m;
    }
}
